#include "Shader.h"
#include <iostream>
#include <fstream>
#include <sstream>

using namespace milo;

Shader::Shader(GLenum eShaderType)
{
	_id = glCreateShader(eShaderType);
	_type = eShaderType;
}

Shader::~Shader(void)
{
	if ( glIsShader( _id ) )
		glDeleteShader( _id );
}

bool Shader::loadFromString(const std::string &strShader)
{
	const char *strFileData = strShader.c_str();
	glShaderSource(_id, 1, &strFileData, NULL);

	glCompileShader(_id);

	GLint status;
	glGetShaderiv(_id, GL_COMPILE_STATUS, &status);
	if (status == GL_FALSE)
	{
		GLint infoLogLength;
		glGetShaderiv(_id, GL_INFO_LOG_LENGTH, &infoLogLength);

		GLchar *strInfoLog = new GLchar[infoLogLength + 1];
		glGetShaderInfoLog(_id, infoLogLength, NULL, strInfoLog);

		const char *strShaderType = NULL;
		switch(_type)
		{
		case GL_VERTEX_SHADER: strShaderType = "vertex"; break;
		case GL_GEOMETRY_SHADER: strShaderType = "geometry"; break;
		case GL_FRAGMENT_SHADER: strShaderType = "fragment"; break;
		}

		fprintf(stderr, "Compile failure in %s shader:\n%s\n", strShaderType, strInfoLog);
		delete[] strInfoLog;
	}
	return true;
}

bool Shader::loadFromFile(const std::string &fileName)
{
	std::ifstream shaderFile(fileName.c_str());
	std::stringstream shaderData;
	shaderData << shaderFile.rdbuf();
	shaderFile.close();

	return (loadFromString( shaderData.str() ));
}

GLuint Shader::getId() const
{
	return _id;
}